#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "wifi_station.h"
#include "tcp_client.h" 
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "cmsis_os2.h"
#include "ohos_init.h"
#include <string.h>
#include <errno.h>

static const char *TAG = "WIFI_STATION";

// WiFi配置
#define WIFI_SSID "XQ-TEST"
#define WIFI_PASSWORD "12345678"

// TCP服务器端口
#define TCP_SERVER_PORT  8080

void WifiStationTask(void) {
    printf("Starting Wi-Fi Station Monitoring...\n");

    // 拉起串口线程
    StartUartTask();
    
    while (1) {
        // 获取当前Wi-Fi状态
        WIFI_STATUS status = GetWifiStatus();
        
        switch (status) {
            case WIFI_STATE_DISCONNECTED:
                printf("Wi-Fi is DISCONNECTED! Attempting to reconnect...\n");
                tcp_client_stop();
                
                // 尝试连接到目标Wi-Fi
                if (ConnectToAP(WIFI_SSID, WIFI_PASSWORD) != 0) {
                    printf("Reconnection failed. Retrying in 10 seconds...\n");
                    sleep(10);
                } else {
                    printf("Reconnection initiated successfully.\n");
                }
                break;
                
            case WIFI_STATE_CONNECTED:
                if (IsWifiConnect()) {
                    // 获取并打印本机IP地址
                    char localIp[16] = {0};
                    GetLocalIpString_app(localIp, sizeof(localIp));
                    printf("Device IP: %s\n", localIp);
                    
                    // 获取并打印网关(AP)IP地址
                    char gatewayIp[16] = {0};
                    GetGatewayIp(gatewayIp, sizeof(gatewayIp));
                    printf("Access Point IP: %s\n", gatewayIp);

                    // 使用网关IP和端口号初始化TCP客户端
                    if (tcp_get_connection_state() != TCP_STATE_CONNECTED) {
                        tcp_client_start(gatewayIp, TCP_SERVER_PORT);
                    }

                    // 处理答题结果并发送
                    if (tcp_get_connection_state() == TCP_STATE_CONNECTED) {
                        process_question_result();
                    }
                    
                } else {
                    printf("Wi-Fi is connected but no IP address assigned\n");
                }
                break;
                
            case WIFI_STATE_INIT:
            default:
                printf("Initializing Wi-Fi connection...\n");
                // 首次连接
                if (ConnectToAP(WIFI_SSID, WIFI_PASSWORD) != 0) {
                    printf("Initial connection failed. Retrying...\n");
                }
                break;
        }
        
        // 休眠5秒后再次检查
        sleep(5);
    }
}

// OpenHarmony入口函数
void WifiStationDemo(void) {
    // 使用CMSIS-RTOS2的线程属性结构体
    osThreadAttr_t attr;
    attr.name = "WIFI_STATION_TASK";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 10240;
    attr.priority = osPriorityNormal;  // 使用CMSIS定义优先级，这里使用普通优先级

    // 创建线程
    if (osThreadNew((osThreadFunc_t)WifiStationTask, NULL, &attr) == NULL) {
        ESP_LOGE(TAG, "Failed to create WiFi station task");
    } else {
        ESP_LOGI(TAG, "WiFi station task created");
    }
}
APP_FEATURE_INIT(WifiStationDemo);